/**
 * 
 */
package cm.mefobe.android.telecomcost;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import cm.mefobe.android.telecomcost.entities.Call;
import cm.mefobe.android.telecomcost.entities.Country;
import cm.mefobe.android.telecomcost.entities.DailyThreshold;
import cm.mefobe.android.telecomcost.entities.Day;
import cm.mefobe.android.telecomcost.entities.DayRangeThreshold;
import cm.mefobe.android.telecomcost.entities.Month;
import cm.mefobe.android.telecomcost.entities.MonthlyThreshold;
import cm.mefobe.android.telecomcost.entities.Provider;
import cm.mefobe.android.telecomcost.entities.Threshold;
import cm.mefobe.android.telecomcost.entities.VoiceRate;
import cm.mefobe.android.telecomcost.entities.Week;
import cm.mefobe.android.telecomcost.entities.WeeklyThreshold;
import cm.mefobe.android.telecomcost.entities.Zone;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Handler;
import android.text.format.DateUtils;
import android.util.Log;

/**
 * @author Administrator
 * 
 */
public class DatabaseManager extends SQLiteOpenHelper {

	private final static String DB_NAME = "telecomcost.db";
	private final static int DB_VERSION = 22;

	/**
	 * @param context
	 * @param name
	 * @param factory
	 * @param version
	 */
	public DatabaseManager(Context context, String name, CursorFactory factory,
			int version) {
		super(context, DB_NAME, factory, DB_VERSION);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
	 * .SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i("DatabaseManager", "Creating the databse...version : "
				+ DB_VERSION);

		String query = "CREATE TABLE json_data (type VARCHAR NOT NULL,json VARCHAR NOT NULL,id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,hash_code VARCHAR NOT NULL);";

		// create the json_data table.
		db.execSQL(query);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
	 * .SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		Log.i("DatabaseManager", "Upgrading the databse to the version : "
				+ DB_VERSION);
		db.execSQL("DROP TABLE json_data");
		onCreate(db);
	}

	public long saveData(String type, String json, long id, int hash_code) {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("type", type);
		values.put("json", json);
		values.put("hash_code", hash_code);

		long _id;

		if (id == -1) // new object
		{
			_id = db.insert("json_data", null, values);
		} else // that object already in db
		{
			_id = db.update("json_data", values, "id = " + id, null);
		}

		db.close();

		return _id;
	}

	public String getData(String type, long id) {
		String json = "";
		SQLiteDatabase db = this.getReadableDatabase();
		String query = "SELECT json,id FROM json_data WHERE type = "
				+ Utility.quote(type) + " AND id = " + Utility.quote(id);
		Cursor cur = db.rawQuery(query, null);

		if (cur.moveToNext()) {
			json = cur.getString(0);
		}

		cur.close();
		db.close();
		return json;
	}

	public String getDataByHashCode(String type, long hashcode) {
		String json = "";
		SQLiteDatabase db = this.getReadableDatabase();
		String query = "SELECT json,id FROM json_data WHERE type = "
				+ Utility.quote(type) + " AND hash_code = "
				+ Utility.quote(hashcode);
		Cursor cur = db.rawQuery(query, null);

		if (cur.moveToNext()) {
			json = cur.getString(0);
		}

		cur.close();
		db.close();
		return json;
	}

	public ArrayList<Call> getCalls(Context context) {
		String[] strFields = { android.provider.CallLog.Calls.CACHED_NAME,
				android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
				android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
				android.provider.CallLog.Calls.CONTENT_ITEM_TYPE,
				android.provider.CallLog.Calls.NUMBER,
				android.provider.CallLog.Calls.DATE,
				android.provider.CallLog.Calls.DURATION };
		String strOrder = android.provider.CallLog.Calls.DATE + " DESC";

		Cursor mCallCursor = context.getContentResolver().query(
				android.provider.CallLog.Calls.CONTENT_URI, strFields, null,
				null, strOrder);

		ArrayList<Call> calls = new ArrayList<Call>();

		// get start of cursor
		if (mCallCursor.moveToFirst()) {

			// loop through cursor
			do {
				Call call = new Call();
				call.setCachedName(mCallCursor.getString(0));
				call.setCachedNumberLabel(mCallCursor.getString(1));
				call.setCachedNumberType(mCallCursor.getString(2));
				call.setDate(mCallCursor.getString(5));
				call.setDuration(mCallCursor.getInt(6));
				call.setNumber(mCallCursor.getString(4));
				calls.add(call);
			} while (mCallCursor.moveToNext());

		}

		return null;
	}

	public long getNextId() {
		long id = 0;
		SQLiteDatabase db = this.getReadableDatabase();
		String query = "SELECT id FROM json_data ORDER BY id DESC";
		Cursor cur = db.rawQuery(query, null);

		if (cur.moveToNext()) {
			id = cur.getLong(0) + 1;
		}

		cur.close();
		db.close();
		return id;
	}

	public Map<String, String> getData(String type) {
		SQLiteDatabase db = this.getReadableDatabase();
		String query = "SELECT json,id FROM json_data WHERE type = "
				+ Utility.quote(type);
		Cursor cur = db.rawQuery(query, null);

		Map<String, String> strings = new HashMap<String, String>();

		int i = 0;
		while (cur.moveToNext()) {
			strings.put(cur.getString(1), cur.getString(0));
			i++;
		}

		cur.close();
		db.close();

		return strings;
	}

	public void deleteData(String type) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete("json_data", "type = " + Utility.quote(type), null);
		db.close();
	}

	public boolean deleteData(String type, long id) {
		SQLiteDatabase db = this.getWritableDatabase();
		int rows = db.delete("json_data", "type = " + Utility.quote(type)
				+ " AND id = " + Utility.quote(id), null);
		db.close();
		return rows > 0;
	}

	public ArrayList<Zone> getZones() {
		Gson gson = TelecomCost.getGson();
		Map<String, String> map = getData(Zone.PROP_TYPE);

		ArrayList<Zone> zones = new ArrayList<Zone>(map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			Zone zone = gson.fromJson(e.getValue(), Zone.class);
			zone.setId(Long.parseLong(e.getKey()));
			zones.add(zone);
		}

		return zones;
	}

	public ArrayList<Threshold> getThresholds() {
		Gson gson = TelecomCost.getGson();
		Map<String, String> map = getData(Threshold.PROP_TYPE);

		ArrayList<Threshold> thresholds = new ArrayList<Threshold>(map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			Threshold threshold = gson.fromJson(e.getValue(), Threshold.class);
			threshold.setId(Long.parseLong(e.getKey()));
			thresholds.add(threshold);
		}

		return thresholds;
	}

	public ArrayList<Country> getCountries() {
		Gson gson = TelecomCost.getGson();
		Map<String, String> map = getData(Country.PROP_TYPE);

		ArrayList<Country> countries = new ArrayList<Country>(map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			Country country = gson.fromJson(e.getValue(), Country.class);
			country.setId(Long.parseLong(e.getKey()));
			countries.add(country);
		}

		return countries;
	}

	public Country getCountryByCode(String code) {
		ArrayList<Country> countries = getCountries();

		int index = 0;
		while (index < countries.size()) {
			if (countries.get(index).getCode().equals(code)) {
				return countries.get(index);
			}

			index++;
		}

		return null;
	}

	public ArrayList<Provider> getProviders() {
		Gson gson = TelecomCost.getGson();
		Map<String, String> map = getData(Provider.PROP_TYPE);

		ArrayList<Provider> providers = new ArrayList<Provider>(map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			Provider provider = gson.fromJson(e.getValue(), Provider.class);
			provider.setId(Long.parseLong(e.getKey()));
			providers.add(provider);
		}

		return providers;
	}

	public void deleteZone(Zone zone) {
		Log.i("DatabaseManager", "deleting zone " + zone.getName() + "...");
		ArrayList<Country> countries = zone.getCountries();

		int index = 0;
		while (index < countries.size()) {
			deleCountry(countries.get(index));
			index++;
		}

		Log.i("DatabaseManager",
				deleteData(Zone.PROP_TYPE, zone.getId()) ? zone.getName()
						+ " deleted..." : "could not deleted zone "
						+ zone.getName());
	}

	public void deleCountry(Country country) {
		Log.i("DatabaseManager", "deleting country " + country.getName()
				+ "...");
		Gson gson = TelecomCost.getGson();
		Zone zone = gson.fromJson(getData(Zone.PROP_TYPE, country.getZoneId()),
				Zone.class);
		if (zone != null) {
			if (zone.remove(country)) {
				saveZone(zone, zone.getId());
			} else {
				Log.i("CountryListActivity", "could not remove the country "
						+ country.getName() + " from zone " + zone.getName());
			}
		} else {
			Log.i("CountryListActivity",
					"could not load the zone of the country "
							+ country.getName());
		}

		ArrayList<Provider> providers = country.getProviders();

		int index = 0;
		while (index < providers.size()) {
			Log.i("DatabaseManager", "deleting provider "
					+ providers.get(index).getName() + "...");
			deleteData(Provider.PROP_TYPE, providers.get(index).getId());
			index++;
		}

		deleteData(Country.PROP_TYPE, country.getId());
	}

	public boolean saveCountry(Country country, long id) {
		Log.i("DatabaseManager", "saving country " + country.getName());
		Gson gson = TelecomCost.getGson();
		Zone zone = gson.fromJson(getData(Zone.PROP_TYPE, country.getZoneId()),
				Zone.class);
		if (zone == null) {
			Log.i("DatabaseManager", "cannot save this country...zone is null");
			return false;
		}

		if (zone.getId() == -1) {
			Log.i("DatabaseManager",
					"cannot save this country...id of the zone not specified");
			return false;
		}

		if (country == null || country.getName() == null) {
			Log.i("DatabaseManager",
					"cannot save this country...country is null");
			return false;
		}
		if (country.getId() != -1) {
			if (zone.add(country)) {
				Log.i("DatabaseManager",
						"country added to zone " + zone.getName());
				saveZone(zone, zone.getId());
				Log.i("DatabaseManager",
						id == -1 ? "saving country " + country.getName()
								: "updating country " + country.getName());
				saveData(Country.PROP_TYPE, gson.toJson(country), id,
						country.hashCode());
				return true;
			} else {
				Log.i("DatabaseManager", "could not add country to zone "
						+ zone.getName());
				return false;
			}
		}

		Log.i("DatabaseManager", "cannot save this country...set the id first");
		return false;
	}

	public boolean saveZone(Zone zone, long id) {
		if (zone == null) {
			Log.i("DatabaseManager", "cannot save this zone...zone is null");
			return false;
		}

		if (zone.getId() == -1) {
			Log.i("DatabaseManager", "cannot save this zone...set the id first");
			return false;
		}

		Log.i("DatabaseManager", id != -1 ? "updating zone " + zone.getName()
				: "saving zone " + zone.getName());
		Gson gson = TelecomCost.getGson();
		return saveData(Zone.PROP_TYPE, gson.toJson(zone), id, zone.hashCode()) > 0;
	}

	public void saveDailyThreshold(DailyThreshold threshold) {
		if (threshold == null) {
			Log.i("DatabaseManager",
					"cannot save this threshold...threshold is null");
		}

		Log.i("DatabaseManager",
				"saving DailyThreshold for " + threshold.getDayNameLong() + "........." + threshold.getAmount());
		saveData(DailyThreshold.PROP_TYPE,
				TelecomCost.getGson().toJson(threshold), threshold.getId(),
				threshold.getDay().hashCode());
		Log.i("DatabaseManager",
		"we check if the DailyThreshold is saved.....");			
	}

	public boolean saveProvider(Provider provider, Country country, long id) {
		if (provider == null) {
			Log.i("DatabaseManager",
					"cannot save this provider...provider is null");
			return false;
		}

		if (provider.getId() != -1) {
			if (country == null || country.getName() == null) {
				Log.i("DatabaseManager",
						"cannot save this provider...country is null");
				return false;
			}

			Gson gson = TelecomCost.getGson();

			if (country.add(provider)) {
				Log.i("DatabaseManager",
						"provider added to country " + country.getName());
				saveCountry(country, country.getId());
				Log.i("DatabaseManager",
						id == -1 ? "saving provider " + provider.getName()
								: "updating provider " + provider.getName());
				saveData(Provider.PROP_TYPE, gson.toJson(provider), id,
						provider.hashCode());
				return true;
			} else {
				Log.i("DatabaseManager",
						"could not add the provider " + provider.getName()
								+ " to country " + country.getName());
				return false;
			}
		}

		Log.i("DatabaseManager", "cannot save this provider...set the id first");
		return false;
	}

	public boolean saveCountry(Country country, Zone zone, long id) {
		Gson gson = TelecomCost.getGson();
		if (zone == null) {
			Log.i("DatabaseManager", "cannot save this country...zone is null");
			return false;
		}

		if (zone.getId() == -1) {
			Log.i("DatabaseManager",
					"cannot save this country...id of the zone not specified");
			return false;
		}

		if (country == null || country.getName() == null) {
			Log.i("DatabaseManager",
					"cannot save this country...country is null");
			return false;
		}
		if (country.getId() != -1) {
			if (zone.add(country)) {
				Log.i("DatabaseManager",
						"country added to zone " + zone.getName());
				saveZone(zone, zone.getId());
				Log.i("DatabaseManager",
						id == -1 ? "saving country " + country.getName()
								: "updating country " + country.getName());
				saveData(Country.PROP_TYPE, gson.toJson(country), id,
						country.hashCode());
				return true;
			} else {
				Log.i("DatabaseManager", "could not add country to zone "
						+ zone.getName());
				return false;
			}
		}

		Log.i("DatabaseManager", "cannot save this country...set the id first");
		return false;
	}

	public ArrayList<MonthlyThreshold> getMonthlyThreshold() {
		ArrayList<MonthlyThreshold> thresholds = getMonthlyThresholds();

		ArrayList<MonthlyThreshold> return_thresholds = new ArrayList<MonthlyThreshold>();

		return_thresholds
				.add(getMonthlyThreshold(Calendar.JANUARY, thresholds));

		return_thresholds
				.add(getMonthlyThreshold(Calendar.FEBRUARY, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.MARCH, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.APRIL, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.MAY, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.JUNE, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.JULY, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.AUGUST, thresholds));

		return_thresholds.add(getMonthlyThreshold(Calendar.SEPTEMBER,
				thresholds));

		return_thresholds
				.add(getMonthlyThreshold(Calendar.OCTOBER, thresholds));

		return_thresholds
				.add(getMonthlyThreshold(Calendar.NOVEMBER, thresholds));

		return_thresholds
				.add(getMonthlyThreshold(Calendar.DECEMBER, thresholds));

		return return_thresholds;
	}

	public MonthlyThreshold getMonthlyThreshold(int monthOfYear,
			ArrayList<MonthlyThreshold> thresholds) {
		Log.i("DatabaseManager",
				"loading MonthlyThreshold for "
						+ DateUtils.getMonthString(monthOfYear,
								DateUtils.LENGTH_LONG));

		int index = 0;
		while (index < thresholds.size()) {
			MonthlyThreshold theshold = thresholds.get(index);
			if (theshold.getMonth().getMonthOfYear() == monthOfYear) {
				return theshold;
			}
			index++;
		}

		Month month = new Month(monthOfYear);
		return new MonthlyThreshold(0, month );
	}

	private ArrayList<MonthlyThreshold> getMonthlyThresholds() {
		Log.i("DatabaseManager", "getMonthlyThresholds...");
		Gson gson = TelecomCost.getGson();
		Map<String, String> map = getData(MonthlyThreshold.PROP_TYPE);

		ArrayList<MonthlyThreshold> thresholds = new ArrayList<MonthlyThreshold>(
				map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			MonthlyThreshold threshold = gson.fromJson(e.getValue(),
					MonthlyThreshold.class);
			threshold.setId(Long.parseLong(e.getKey()));
			thresholds.add(threshold);
		}

		return thresholds;
	}

	public void saveDayRangeThreshold(DayRangeThreshold threshold, ProgressDialog mProgressDialog, Handler mProgressHandler) {
		if (threshold == null) {
			throw new InvalidParameterException(
					"cannot save this threshold...threshold is null");
		}

		ArrayList<DailyThreshold> thresholds = threshold.getDailyThresholds();
//		mProgressDialog.show();
//		mProgressDialog.setMax(thresholds.size());
		
		double totalAmount = threshold.getCalculatedAmount();

		double difference = 0;
		int index = 0;
		int amountToDispatch = 0;
		
		if (totalAmount > threshold.getAmount()) {
			Log.i("DatabaseManager",
					"the total amount of the DailyThreshold thresholds for this DayRange "
							+ totalAmount
							+ " is greater than the DayRange threshold amount "
							+ threshold.getAmount());
			difference = totalAmount - threshold.getAmount();
			amountToDispatch = (int) (difference / thresholds.size());			
			
			while (index < thresholds.size()) {
				DailyThreshold dailyThreshold = thresholds.get(index);
				Log.i("DatabaseManager", "we remove " + amountToDispatch
						+ " from DailyThreshold threshold for day "
						+ dailyThreshold.getDay().toString());
				dailyThreshold.setAmount(dailyThreshold.getAmount()
						- amountToDispatch);
				saveDailyThreshold(dailyThreshold);
//				mProgressDialog.setTitle(dailyThreshold.getDay().toString() + " - " + dailyThreshold.getAmount());
//				mProgressHandler.sendEmptyMessage(0);
				index++;
			}
		}

		if (totalAmount < threshold.getAmount()) {
			Log.i("DatabaseManager",
					"the total amount of the DailyThreshold thresholds for this DayRange "
							+ totalAmount
							+ " is lower than the DayRange threshold amount "
							+ threshold.getAmount());
			difference = threshold.getAmount() - totalAmount;

			amountToDispatch = (int) (difference / thresholds.size());

			while (index < thresholds.size()) {
				DailyThreshold dailyThreshold = thresholds.get(index);
				
				Log.i("DatabaseManager", "we add " + amountToDispatch
						+ " to dailyThreshold for "
						+ dailyThreshold.getDay().toString());
				dailyThreshold.setAmount(dailyThreshold.getAmount()
						+ amountToDispatch);
				saveDailyThreshold(dailyThreshold);
//				mProgressDialog.setTitle(dailyThreshold.getDay().toString() + " - " + dailyThreshold.getAmount());
//				mProgressHandler.sendEmptyMessage(0);
				index++;
			}
		}
	}
	
	
	public MonthlyThreshold saveMonthlyThreshold(MonthlyThreshold threshold, ProgressDialog mProgressDialog, Handler mProgressHandler) {										
		String month = DateUtils.getMonthString(threshold.getMonth()
				.getMonthOfYear(), DateUtils.LENGTH_LONG);
		Log.i("DatabaseManager",
				threshold.getId() != -1 ? "updating threshold for " + month
						: "saving threshold for " + month);

		saveData(MonthlyThreshold.PROP_TYPE,
				TelecomCost.getGson().toJson(threshold), threshold.getId(),
				threshold.getMonth().hashCode());
		
		return threshold;
	}

	public ArrayList<Provider> getCountryProviders(Country country) {
		Log.i("DatabaseManager",
				"loading providers for country..." + country.getName());
		ArrayList<Provider> providers = new ArrayList<Provider>();
		int index = 0;

		while (index < country.getProviderIds().length) {
			String json = getData(Provider.PROP_TYPE,
					country.getProviderIds()[index]);

			if (!json.equals("")) {
				Provider provider = TelecomCost.getGson().fromJson(json,
						Provider.class);
				provider.setId(country.getProviderIds()[index]);
				providers.add(provider);

				Log.i("DatabaseManager", "........" + provider.getName());
			}

			index++;
		}

		return providers;
	}

	public ArrayList<Country> getZonesCountries(Zone zone) {
		Log.i("DatabaseManager",
				"loading countries for zone..." + zone.getName() + "...ids"
						+ zone.getCountriesIds());
		ArrayList<Country> countries = new ArrayList<Country>(
				zone.getCountriesIds().length);
		int index = 0;

		while (index < zone.getCountriesIds().length) {
			String json = getData(Country.PROP_TYPE,
					zone.getCountriesIds()[index]);

			if (!json.equals("")) {
				Country country = TelecomCost.getGson().fromJson(json,
						Country.class);
				country.setId(zone.getCountriesIds()[index]);
				countries.add(country);
				Log.i("DatabaseManager", "........." + country.getName());
			}

			index++;
		}

		return countries;
	}

	public ArrayList<VoiceRate> getVoiceRates() {
		Map<String, String> map = getData(VoiceRate.PROP_TYPE);

		ArrayList<VoiceRate> rates = new ArrayList<VoiceRate>(map.size());

		for (Map.Entry<String, String> e : map.entrySet()) {
			VoiceRate rate = TelecomCost.getGson().fromJson(e.getValue(),
					VoiceRate.class);
			rate.setId(Long.parseLong(e.getKey()));
			rates.add(rate);
		}

		return rates;
	}

	public ArrayList<Call> getCallsByDate(Date date, Context context) {
		String[] strFields = { android.provider.CallLog.Calls.CACHED_NAME,
				android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
				android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
				android.provider.CallLog.Calls.CONTENT_ITEM_TYPE,
				android.provider.CallLog.Calls.NUMBER,
				android.provider.CallLog.Calls.DATE,
				android.provider.CallLog.Calls.DURATION };
		String strOrder = android.provider.CallLog.Calls.DATE + " DESC";

		Cursor mCallCursor = context.getContentResolver().query(
				android.provider.CallLog.Calls.CONTENT_URI, strFields, null,
				null, strOrder);

		ArrayList<Call> calls = new ArrayList<Call>();

		// get start of cursor
		if (mCallCursor.moveToFirst()) {

			// loop through cursor
			do {
				Call call = new Call();
				call.setCachedName(mCallCursor.getString(0));
				call.setCachedNumberLabel(mCallCursor.getString(1));
				call.setCachedNumberType(mCallCursor.getString(2));
				call.setDate(mCallCursor.getString(5));
				call.setDuration(mCallCursor.getInt(6));
				call.setNumber(mCallCursor.getString(4));
				calls.add(call);
				Log.i("DatabaseManager", call.toString());
			} while (mCallCursor.moveToNext());

		}

		return null;
	}

	public DailyThreshold getDayThreshold(Day day) {		
		DailyThreshold limit = TelecomCost.getGson().fromJson(
				getDataByHashCode(DailyThreshold.PROP_TYPE, day.hashCode()),
				DailyThreshold.class);

		DailyThreshold limite = limit != null ? limit : new DailyThreshold(0, day);
		Log.i("DatabaseManager", "loading DailyThreshold for " + day.toString() + "---" + limite.getAmount());
		return limite;
	}

	public WeeklyThreshold getWeekThreshold(Week week) {
		Log.i("DatabaseManager", "loading WeekThreshold for " + week.toString());

		WeeklyThreshold limit = TelecomCost.getGson().fromJson(
				getDataByHashCode(WeeklyThreshold.PROP_TYPE, week.hashCode()),
				WeeklyThreshold.class);

		return limit != null ? limit : new WeeklyThreshold(0, week);
	}

	public void saveWeeklyThreshold(WeeklyThreshold threshold) {
		//saveDayRangeThreshold(threshold);

		Log.i("DatabaseManager",
				threshold.getId() != -1 ? "updating threshold for "
						+ threshold.getWeek().getName()
						: "saving threshold for "
								+ threshold.getWeek().getName());

		saveData(WeeklyThreshold.PROP_TYPE,
				TelecomCost.getGson().toJson(threshold), threshold.getId(),
				threshold.getWeek().hashCode());
	}
}
